import { defineStore } from 'pinia'
import md5 from 'md5'

import { login } from '@/api/sys'
import { getItem, setItem } from '@/utils/storage'
import { TOKEN } from '@/constant'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: (getItem(TOKEN) || '') as string
  }),
  actions: {
    actionLogin({ username, password }: { username: string; password: string }) {
      return new Promise<void>((resolve, reject) => {
        login({ username, password: md5(password) })
          .then((data: any) => {
            this.token = data.token
            // 存入 localStorage
            setItem(TOKEN, this.token)

            resolve()
          })
          .catch(reject)
      })
    }
  }
})
